const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    deviceName:'',
    deviceCode:'',
    location:'',
    netName:'',
    phone:'',
    goodsList: [{
      id: 1,
      image: 'https://via.placeholder.com/150', // 占位图，可替换为实际图片
      channelName: '货道 A1',
      name: '可口可乐'
    },
    {
      id: 2,
      image: 'https://via.placeholder.com/150',
      channelName: '货道 A2',
      name: '雪碧'
    },
    {
      id: 3,
      image: 'https://via.placeholder.com/150',
      channelName: '货道 A3',
      name: '农夫山泉'
    },
    {
      id: 4,
      image: 'https://via.placeholder.com/150',
      channelName: '货道 A4',
      name: '红牛'
    },
    {
      id: 5,
      image: 'https://via.placeholder.com/150',
      channelName: '货道 B1',
      name: '康师傅绿茶'
    },
    {
      id: 6,
      image: 'https://via.placeholder.com/150',
      channelName: '货道 B2',
      name: '统一冰红茶'
    },
    {
      id: 7,
      image: 'https://via.placeholder.com/150',
      channelName: '货道 B3',
      name: '怡宝'
    },
    {
      id: 8,
      image: 'https://via.placeholder.com/150',
      channelName: '货道 B4',
      name: '芬达'
    }]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options.id)
    this.getDeviceDetail(options.id)
    this.getDeviceList(options.id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

    //获取设备详情
    getDeviceDetail(id){
      this.requestHttp('/app/client/manage/device/detail', {'deviceId': id}, 'get').then((data) => {
        console.log(data)
        this.setData({
          deviceName: data.data.name,
          deviceCode: data.data.deviceCode,
          location: data.data.position,
          netName: data.data.tenantName,
          phone: data.data.iotCardNumber,
        });
      })
    },
   //获取商品列表
   getDeviceList(id){
    this.requestHttp('/app/client/manage/device/cargo/list', {'deviceId': id}, 'POST').then((data) => {
      console.log(data)
      this.setData({
        goodsList: data
      })
    })
  },

  //一键调试
  async oneJian(){
    console.log(12345)
    const idList = this.data.goodsList.map(item => item.id); // 假设这里有 100 个 cargoId

  for (const id of idList) {
    console.log("调试 cargoId:", id);

    try {
      const data = await this.requestHttp(
        '/app/client/manage/device/cargo/out',
        { cargoId: id },
        'GET'
      );

      if (data.code === 0) {
        wx.showToast({ title: `调试成功: ${id}`, icon: 'success' });
      } else {
        wx.showToast({ title: `失败: ${data.msg}`, icon: 'none' });
      }
    } catch (err) {
      console.error("请求出错:", err);
      wx.showToast({ title: `请求错误: ${id}`, icon: 'none' });
    }

    // 给接口一个间隔，避免并发或频率限制（可选）
    await this.sleep(300); // 300ms 间隔
  }
  },

  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  },

  goGoods(e){
    const index = e.currentTarget.dataset.index;
    const item = this.data.goodsList[index];
    console.log('当前商品信息：', item);
    wx.navigateTo({
      url: `/pages/devicegoods/devicegoods?number=${item.number}&id=${item.id}&goodsName=${item.goodsName}&goodsId=${item.goodsId}&goodsPrice=${item.goodsPrice}&goodsDiscount=${item.goodsDiscount}&goodsStock=${item.goodsStock}&id=${item.id}&status=${item.status}&deviceId=${item.deviceId}`,
    })
  },

  onDebug(e){
    console.log(e.currentTarget.dataset.id);
    this.requestHttp('/app/client/manage/device/cargo/out', {'cargoId': e.currentTarget.dataset.id}, 'GET').then((data) => {
      console.log(data)
      if (data.code === 0) {
        wx.showToast({
          title: '调试成功',
        })
      } else {
        wx.showToast({
          title: data.msg,
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  requestHttp(url, data = {}, method = 'GET') {
    return new Promise(function (resolve, reject) {
      const headers = {
        'Authorization': app.globalData.token || '',
        'Content-Type': 'application/x-www-form-urlencoded'
      };
  
      wx.request({
        url: app.globalData.host + url,
        method: method.toUpperCase(),
        data,
        header: headers,
        success(res) {
          const data = res.data;
          resolve(data);
        },
        fail(err) {
          wx.showToast({
            title: '网络请求失败',
            icon: 'error',
          });
          reject(err);
        }
      });
    });
  }  
})